MusicBrainz = {};
MusicBrainz = function()
{
  this.search_result;
  this.ajax =  new Ajax();
  this.target;
  this.art = '';
  this.tle = '';
  this.MAX = 2;
  this.results = 0;
  this.total_pages;
  this.attempts = 0;
  this.current_page=0;
  this.artist_id;
  this.release_id;
  this.artist_result;
  this.getCover = true;
  
  window.mb = this;
}

MusicBrainz.inherits(WebService);

MusicBrainz.prototype.viewPage = function(number)
{
  this.current_page = number;
  this.target.innerHTML = this.displayList();
}

MusicBrainz.prototype.abort = function() 
{ 
	if(this.ajax.http) this.ajax.http.abort(); 
	this.target.innerHTML = '<h3>You have cancelled the MusicBrainz search. To force the insertion of your song "as it is" <a href="javascript:Add.force(1)">clicking here</a>.</h3>'; 
}

MusicBrainz.prototype.search = function(artist, title)
{
  if(!this.art){
    this.art = artist;
    this.tle = title;
  }
  var m = this;

  var options = {target: m.target, timeout: 0,
  		  onTimeOut: function(){Add.reset(1)}, 
          onLoading:function(o,target){ mt.onLoading(target,'Searching song '+title+' by '+artist+' in the MusicBrainz database.<br /><b>This might take a while, please be patient</b><br /><a href="javascript:mb.abort();Add.reset(1);"><b>Cancel</b></a> ');},
          onError: function(o,target,str){ },
          onComplete:function(o,target){m.search_result = o.responseXML; try{target.innerHTML = m.showTrackList();}catch(e){alert(e)}},        
          data: 'artist='+artist+'&title='+title+'&op=brainz'};

   this.ajax.makeRequest('proxy.php', options);
} 

MusicBrainz.prototype.showTrackList = function()
{
  var tracks = this.search_result.getElementsByTagName('track');
  var html = '<div class="tracklist">';
  if(tracks.length){
    html += '<h3>'+(tracks.length>1?
              'Here are some matching titles: choose the most accurate one':
              'We found this track matching the information provided')+
            '<br />If you can\'t find any matching titles please \
            double check the <a href="javascript:Add.reset(1)">information provided</a>. If you <b>can\'t</b> find your song in the following list you can add your song by<a href="javascript:Add.force()">clicking here</a>.</h3>';
  }
  else {
    
    html += 'No tracks found. Please double check the spelling or, if sure about the correctnessof the information provided, <a href="Add.force()">add the song as it is</a>.';
    //mt.track.reset(1);
    return html;
  }
  
  html +='<table cellspacing="0" cellpadding="2"><tr class="thead"><td>Score&nbsp;%</td><td>Track</td><td>Artist</td><td>Release</td>'
  
  for(var t=0; t<tracks.length; t++){
    var title = tracks[t].getElementsByTagName('title')[0].firstChild.nodeValue;
    var track_id = tracks[t].getAttribute('id');
    var score = tracks[t].getAttribute('ext:score') ? tracks[t].getAttribute('ext:score') : '';
    var artist = tracks[t].getElementsByTagName('artist')[0].getElementsByTagName('name')[0].firstChild.nodeValue;
    var artist_id = tracks[t].getElementsByTagName('artist')[0].getAttribute('id');
    var release = tracks[t].getElementsByTagName('release')[0].getElementsByTagName('title')[0].firstChild.nodeValue;;
    var release_id = tracks[t].getElementsByTagName('release')[0].getAttribute('id');
    
    //the propeties name have to match with db fields!
    mt.track.info[t] = { 'title':title, 'mb_id':track_id, 'artist': artist,'mb_artist_id': artist_id, 'release': release, 'mb_rel_id':release_id };
    
    html += '<tr onclick="Add.select('+t+')" class="'+((t+1)%2?'odd':'even')+'"><td>'+score+'</td><td><strong>'+title+'</strong></td><td>'+artist+'</td><td>'+release+'</td></tr>';
  }
  
  return html+'</table></div>';
}

MusicBrainz.prototype.show = function()
{ 
  try{
    var release = this.search_result.getElementsByTagName('release')[0];
    var release_type = release.getAttribute('type');
    this.release_id = release.getAttribute('id');
    var release_title = release.getElementsByTagName('title')[0].firstChild.nodeValue;
    try {this.asin = release.getElementsByTagName('asin')[0].firstChild.nodeValue;} catch(e){}
    this.artist_id = release.getElementsByTagName('artist')[0].getAttribute('id');
    this.artist_name = release.getElementsByTagName('artist')[0].getElementsByTagName('name')[0].firstChild.nodeValue;
    this.track_list = release.getElementsByTagName('track-list')[0].childNodes;
    var relation_list = release.getElementsByTagName('relation-list');
    try{var release_event = release.getElementsByTagName('release-event-list')[0].getElementsByTagName('event')[0];
    var release_date = release_event.getAttribute('date');
    var release_country = release_event.getAttribute('country');
    }catch(x){var release_date = ''; var release_country='';}
    //get album Cover
    try{
      if(this.getCover){
        if(typeof  window.cover != 'object')  window.cover = new AmazonCovers();
        window.cover.asin = this.asin?this.asin:null;
        window.cover.album = release_title;
        window.cover.search(this.artist_name,this.tle);
      }
    }catch(e){}
    var links = 0;
    for(var rl=0; rl<relation_list.length; rl++){ if(relation_list[rl].getAttribute('target-type')=='Url'){ var relation_list = relation_list[rl].childNodes; links=1; break; } }
    
  }catch(e){
    try{
      if(this.getCover){
        if(typeof  window.cover != 'object')  window.cover = new AmazonCovers();
        window.cover.album = 0;
        window.cover.search(this.art,this.tle);
      }
    }catch(e){}
    //if(this.search_result.getElementsByTagName('mb')[0].getAttribute('res') == 'no match'){
      return '<strong>Sorry, no match with artist/songname (too little information or maybe a spelling error?)</strong>';
    //}
  }
  var html = '';
  
  html +='<p style="font-weight:bold;"><a href="javascript:_mb.getInfo(\'artist\',\''+this.artist_id+'\')">'+this.artist_name+'</a></p>'+
         '<p><b>'+release_title+'</b> (release date: '+release_date+', country: '+release_country+')</p><p><a href="javascript:_mb.getInfo(\'artist\',\''+this.artist_id+'\')">see all releases</a></p>';
  if(links){
    html += '<p class="nav">';
    for(var r=0; r<relation_list.length;r++){
      html += '<a target="_blank" href="'+relation_list[r].getAttribute('target')+'">'+(relation_list[r].getAttribute('type').indexOf('Amazon')>-1?'Buy from Amazon':relation_list[r].getAttribute('type'))+'</a>';
      if(r<relation_list.length-1 ) html += ' | ';
      else html += '</p>';
    }
    
  }
  html +='<table style="margin-top:10px;"><tr><td>#</td><td>Title</td><td>Duration (sec)</td></tr>'
  for(var t=0; t<this.track_list.length; t++){
    var duration_total = parseInt(this.track_list[t].getElementsByTagName('duration')[0].firstChild.nodeValue)/1000;
    var duration_s = parseInt(duration_total % 60);
    duration_total = parseInt(duration_total/60);
    html += '<tr><td>'+(t+1)+'</td><td>'+this.track_list[t].getElementsByTagName('title')[0].firstChild.nodeValue+'</a></td><td>'
        +duration_total+':'+(duration_s>9?duration_s:'0'+duration_s)
        +'</td></tr>';
  }
  html += '</table>';
  
  return html;
}

MusicBrainz.prototype.getInfo = function(what, id)
{
  this.getCover = false;
  
  switch(what){
    case 'track':
     //
    break;
    case 'release':
     if(id == this.release_id){
       this.show();
       return;
     }
     this.release_id = id;
     this.search();
    break;
    case 'artist':
      if(id == this.artist_id && this.artist_result){ this.target.innerHTML = this.showArtist(id); return; }
      var m = this;
      var options = {target: m.target, timeout: 0, 
        onLoading:function(o,target){ onloading(target);},
        onError: function(o,target,str){m.error(str) },
        onComplete:function(o,target){m.artist_result = o.responseXML; try{m.target.innerHTML = m.showArtist(id);}catch(e){alert(e)}},        
        data: 'artist_id='+id+'&artist=&title=&op=brainz'};
    
    this.ajax.makeRequest('proxy.php', options);
    break;
  }
}

MusicBrainz.prototype.showArtist = function(id)
{
 var artist_type = this.artist_result.getElementsByTagName('artist')[0].getAttribute('type');
 var start_date =  this.artist_result.getElementsByTagName('artist')[0].getElementsByTagName('life-span')[0].getAttribute('begin');
 var end_date = this.artist_result.getElementsByTagName('artist')[0].getElementsByTagName('life-span')[0].getAttribute('end');
 var releases = this.artist_result.getElementsByTagName('artist')[0].getElementsByTagName('release');
 
 html = '<p style="font-weight:bold;">'+this.artist_name+'</p>';
 if(artist_type == 'Person') html += '('+start_date+' - '+(end_date?end_date:' ')+')';
 else html += '(group founded: '+start_date+(end_date?', ended: '+end_date:'')+')';
 if(releases.length){
   html += '<p>'+releases.length+' official releases'+'</p>';
   
   for(var r=0; r<releases.length;r++){
     var rel_id = releases[r].getAttribute('id');
     html += '<p><a href="javascript:_mb.getInfo(\'release\',\''+rel_id+'\')">'+releases[r].getElementsByTagName('title')[0].firstChild.nodeValue+'</a> ('+releases[r].getAttribute('type')+')<br />';
     try{
       var relation_list = releases[r].getElementsByTagName('relation-list')[0].childNodes;
       for(var s=0; r<relation_list.length;r++){
         html += '<a target="_blank" href="'+relation_list[s].getAttribute('target')+'">'+(relation_list[s].getAttribute('type').indexOf('Amazon')>-1?'Buy from Amazon':relation_list[s].getAttribute('type'))+'</a>';
         if(s<relation_list.length-1 ) html += ' | ';
         else html += '</p>';
       }
     }catch(q){}
     html += '</p>';
   }
   return html;
 }
}
